package grpcserver

import (
	"net"

	"gitee.com/amwfhv/tge/log"
	"gitee.com/amwfhv/tge/options"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type GrpcServer struct {
	*grpc.Server
	address string
}

func NewGrpcServer(c *options.GRPCOptions) (*GrpcServer, error) {
	creds, err := credentials.NewServerTLSFromFile(c.CertFile, c.KeyFile)
	if err != nil {
		log.Fatalf("Failed to generate credentials %s", err.Error())
		return nil, err
	}
	opts := []grpc.ServerOption{grpc.MaxRecvMsgSize(c.MaxMsgSize), grpc.Creds(creds)}
	s := grpc.NewServer(opts...)

	return &GrpcServer{s, c.Address}, nil
}

func (s *GrpcServer) Run() error {
	listen, err := net.Listen("tcp", s.address)
	if err != nil {
		log.Fatalf("failed to listen: %s", err.Error())
		return err
	}

	log.Infof("start grpc server at %s", s.address)
	if err = s.Serve(listen); err != nil {
		log.Fatalf("failed to start grpc server: %s", err.Error())
		return err
	}
	return nil
}

func (s *GrpcServer) Close() {
	s.GracefulStop()
	log.Infof("GRPC server on %s stopped", s.address)
}
